package com.auth.pojo.dto;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 登录用户信息
 * 适配 Spring Boot 3.x 和 Spring Security 6.x
 * 支持动态路由和菜单权限控制
 *
 * author wangbaohai
 */
@Data
public class SecurityUserDTO implements UserDetails {
    /**
     * ID
     */
    private Long id;
    /**
     * 用户名
     */
    private String username;
    /**
     * 用户代码
     */
    private String userCode;
    /**
     * 用户密码
     */
    private String password;
    /**
     * 用户状态
     */
    private Boolean enabled;
    /**
     * 权限数据
     */
    private Collection<SimpleGrantedAuthority> authorities;
    
    /**
     * 用户菜单权限
     */
    private List<Map<String, Object>> menus;

    public SecurityUserDTO() {

    }

    /**
     * 使用角色和菜单列表构造安全用户对象
     * 
     * @param roles 角色列表
     * @param menus 菜单列表
     */
    public SecurityUserDTO(List<String> roles, List<Map<String, Object>> menus) {
        // 设置权限
        if (roles != null && !roles.isEmpty()) {
            authorities = new ArrayList<>();
            roles.forEach(item -> authorities.add(new SimpleGrantedAuthority(item)));
        }
        
        // 设置菜单
        this.setMenus(menus);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled != null && this.enabled;
    }
}
